package edu.yuhf.dao.mysql;

import java.util.List;

import org.apache.log4j.Logger;

import com.yuhf.dbutils.JdbcTemplate;
import com.yuhf.dbutils.ResultSetHandler;

import edu.yuhf.dao.convert.RoleHandler;
import edu.yuhf.dao.iface.RoleDao;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.Role;

public class RoleJdbcDaoImpl implements RoleDao {

	private static Logger log=Logger.getLogger(RoleJdbcDaoImpl.class);
	
	public void queryRoles(Page<List<Role>> page) {
		String sql="select * from umm_role where 1=1 ";
		if(!"".equals(page.getKeyword())) {
			sql+="and role_name=? or remark like ?";
		}
		sql+="limit ?,?";
		List<Role> list=null;
		ResultSetHandler<List<Role>> rsh=new RoleHandler();
		if(!"".equals(page.getKeyword())) {
			list=JdbcTemplate.query(sql, rsh,page.getKeyword(),"%"+page.getKeyword()+"%",(page.getCurrentPage()-1)*page.getPageNumber(),page.getPageNumber());
		}else {
			list=JdbcTemplate.query(sql, rsh,(page.getCurrentPage()-1)*page.getPageNumber(),page.getPageNumber());
		}
		page.setList(list);
	}
	
	@Override
	public int queryTotalRowNumber(Page<List<Role>> page) {
		int totalRowNumber=0;
		String sql="select count(*) from umm_role where 1=1 ";
		if(!"".equals(page.getKeyword())) {
			sql+="and role_name=? or remark like ?";
			totalRowNumber=JdbcTemplate.queryForCount(sql,page.getKeyword(),page.getKeyword());
		}else {
			totalRowNumber=JdbcTemplate.queryForCount(sql);
		}
		return totalRowNumber;
	}

	@Override
	public int insertRole(Role role) {
		int rowNumber=0;
		String sql="insert into umm_role(role_name,remark) values(?,?)";
		rowNumber=JdbcTemplate.update(sql, role.getRoleName(),role.getRemark());
		return rowNumber;
	}

	@Override
	public int deleteRoles(String ids) {
		int rowNumber=0;
		String sql="delete from umm_role where id in("+ids+")";
		rowNumber=JdbcTemplate.update(sql);
		return rowNumber;
	}

	@Override
	public Role queryRoleById(int id) {
		Role role=null;
		String sql="select id,role_name,remark from role where id=?";
		ResultSetHandler<List<Role>> rsh=new RoleHandler();
		List<Role> list=JdbcTemplate.query(sql, rsh, id);
		if(null!=list&&list.size()!=0){
			role=list.get(0);
		}
		return role;
	}

	@Override
	public int updateRole(Role role) {
		int rowNumber=0;
		String sql="update umm_role set role_name=?,remark=? where id=?";
		rowNumber=JdbcTemplate.update(sql, role.getRoleName(),role.getRemark(),role.getId());
		return rowNumber;
	}

	@Override
	public List<Role> queryRolesByUserId(int userId) {
		String sql="select * from role r inner join umm_user_role ur on r.id=ur.role_id where ur.user_id=?";
		List<Role> list=JdbcTemplate.query(sql, new RoleHandler(), userId);
		return list;
	}

	@Override
	public List<Role> queryRoles() {
		String sql="select * from umm_role";
		List<Role> list=null;
		ResultSetHandler<List<Role>> rsh=new RoleHandler();
		list=JdbcTemplate.query(sql, rsh);
		return list;
	}
}
